import React, { forwardRef, useImperativeHandle } from 'react';
import { ProForm, ProFormText } from '@ant-design/pro-components';
import { message } from 'antd';
import { LockOutlined, UserOutlined } from '@ant-design/icons';
import { register } from '@/services/ant-design-pro/api';
import { createStyles } from 'antd-style';
import { history } from '@umijs/max';

// 定义样式
const useStyles = createStyles(() => ({
  formWrapper: {
    width: '100%',
  },
}));

// 正确使用 forwardRef，并传递类型
const Register = forwardRef<any, {
  onFinish?: (values: API.RegisterParams) => void;
  onRegisterSuccess?: () => void; // 新增回调函数
}>((props, ref) => {
  const { styles } = useStyles();
  const [form] = ProForm.useForm();

  // 使用 useImperativeHandle 暴露 submit 方法
  useImperativeHandle(ref, () => ({
    submit: async () => {
      const values = await form.validateFields();
      await handleSubmit(values);
    },
  }));

  // 注册提交方法
  const handleSubmit = async (values: API.RegisterParams) => {
    try {
      // 调用 API 注册接口
      const result = await register({ ...values });

      // 提取实际的ID值 - 使用类型断言来处理 TypeScript 类型问题
      let userId = null;

      // 检查各种可能的数据结构
      if ((result as any)?.id) {
        userId = (result as any).id;
      } else if ((result as any)?.data?.id) {
        userId = (result as any).data.id;
      } else if ((result as any)?.result?.id) {
        userId = (result as any).result.id;
      } else if (typeof result === 'number' && result > 0) {
        userId = result;
      } else if (typeof result === 'string' && !isNaN(Number(result)) && Number(result) > 0) {
        userId = Number(result);
      }

      // 判断注册是否成功
      const isSuccess = userId && (Number(userId) > 0);

      if (isSuccess) {
        message.success('注册成功！');
        setTimeout(() => {
          // 调用父组件传递的回调函数，切换到登录标签页
          if (props.onRegisterSuccess) {
            props.onRegisterSuccess();
          }
        }, 1000);
      } else {
        const errorMsg = (result as any)?.message || (result as any)?.msg || (result as any)?.error || '注册失败，请重试！';
        message.error(errorMsg);
      }
    } catch (error) {
      console.error('注册错误:', error);
      // 检查是否是网络错误还是业务错误
      if ((error as any)?.response?.data?.message) {
        message.error((error as any).response.data.message);
      } else if ((error as any)?.message) {
        message.error((error as any).message);
      } else {
        message.error('注册失败，请重试！');
      }
    }
  };

  return (
    <ProForm form={form} submitter={false}>
      <div className={styles.formWrapper}>
        <ProFormText
          name="userAccount"
          fieldProps={{ size: 'large', prefix: <UserOutlined /> }}
          placeholder="请输入要注册的用户名"
          rules={[{ required: true, message: '用户名是必填项！' }]}
        />
        <ProFormText.Password
          name="userPassword"
          fieldProps={{ size: 'large', prefix: <LockOutlined /> }}
          placeholder="请输入密码"
          rules={[{ required: true, message: '密码是必填项！' }]}
        />
        <ProFormText.Password
          name="checkPassword"
          fieldProps={{ size: 'large', prefix: <LockOutlined /> }}
          placeholder="确认密码"
          rules={[
            { required: true, message: '确认密码是必填项！' },
            ({ getFieldValue }) => ({
              validator(_, value) {
                if (!value || getFieldValue('userPassword') === value) {
                  return Promise.resolve();
                }
                return Promise.reject(new Error('两次输入的密码不一致'));
              },
            }),
          ]}
        />
      </div>
    </ProForm>
  );
});

export default Register;
